package soulagicom.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import soulagicom.model.Avenger;
import soulagicom.repository.AvengerRepository;



@Controller
public class AvengerRegistrationController {

	@Autowired
	private AvengerRepository avengerRepository;




	@RequestMapping("/home")
	public String avengerHome() {
		return "home";

	}

	@RequestMapping("/avengerstrategy")
	public ModelAndView AvengerCreation(
			@RequestParam(value="firstName")String firstName,
			@RequestParam(value="lastName")String lastName,
			@RequestParam(value="phoneNumber")String phoneNumber,
			@RequestParam(value="emailAddress")String emailAddress) {

		
		// 1. We check for duplicate e-mails
		Avenger avengerWithEmail = avengerRepository.findByEmailAddress(emailAddress);
		if (avengerWithEmail != null) {  
			return new ModelAndView("avengercreationerror");
		}
		
		// 2. We persist and forward.
		Avenger newAvenger = new Avenger(lastName, firstName, phoneNumber, emailAddress);
		avengerRepository.persistAvenger(newAvenger);
		ModelAndView mv = new ModelAndView("avengerstrategy");
		mv.addObject("newAvenger", newAvenger);
		return mv;
	}
	

}
